<?php 
/* 
 * Автор: Громов Алексей
 */
require_once('./inc/arr_pt.php');
class imageHashManager extends Base {	
	private $img = null;
	private $filename = null;
	
	private static $imgSalt = '$5$itsaliongetallin$';
		
	//public $hash = null;
	public $data = array(
			'hash' => null,
			'path' => null,
			'width' => 0,
			'height' => 0, 
			'user_id' => 1				
	       );
	
	const SIZE = 400;
	const THRESHOLD = 1000;
	
	public function __constructor() {
		parent::__constructor();
	}
	
	/*
	 * Вычисление хэша
	 */
	public function createHash() {
		//define("SIZE", 400);
		//$img = imagecreatefrompng("./S&L.png");
		//$img3 = imagecreatefrompng("./S&L_mod.png");
		$width = imagesx($this->img);
		$height = imagesy($this->img);
		$this->width = $width;
		$this->height = $height;
		$koeffX = 1;
		$koeffY = 1;
		if ($height > $width) {
			$koeffY = $height / $width;
		} else {
			$koeffX = $width / $height;
		}
		//echo($koeffY.' '.$koeffX.' '.self::SIZE);
		$img2 = imagecreatetruecolor(self::SIZE * $koeffX, self::SIZE * $koeffY);
		imagecopyresampled($img2, $this->img, 0, 0, 0, 0, self::SIZE * $koeffX, self::SIZE * $koeffY, $width, $height);
		/*$width = imagesx($img3);
		$height = imagesy($img3);
		$koeffX = 1;
		$koeffY = 1;
		if ($height > $width) {
			$koeffY = $height / $width;
		} else {
			$koeffX = $width / $height;
		}
		$img4 = imagecreatetruecolor($SIZE * $koeffX, $SIZE * $koeffY);
		imagecopyresampled($img4, $img3, 0, 0, 0, 0, $SIZE * $koeffX, $SIZE * $koeffY, $width, $height);*/
		/*$cmp_points = array();
		for ($i = 1; $i < 100; $i++) {
			$cmp_points[] = array('x' => $i * 3, 'y' => $i * 2);
		}*/
		//global $cmp_points;
		//$ptlen = count($cmp_points);
		//$success = 0;
		$hash_string = '';
		$histogram = array();
		//foreach ($cmp_points as $pt) {
		for ($i = 0; $i < self::SIZE; $i++) {
			for ($j = 0; $j < self::SIZE; $j++) {
				//$px1 = imagecolorat($img2, $pt['x'], $pt['y']);
				$px1 = imagecolorat($img2, $i, $j);
				//$px2 = imagecolorat($img4, $pt['x'], $pt['y']);
				/*$r = ((($px1 >> 16) & 0xFF) - (($px2 >> 16) & 0xFF));
				$g = ((($px1 >> 8) & 0xFF) - (($px2 >> 8) & 0xFF));
				$b = (($px1 & 0xFF) - ($px2 & 0xFF));*/
				$r = ($px1 >> 16) & 0xFF;
				$g = ($px1 >> 8) & 0xFF;
				$b = $px1 & 0xFF;
				$histogram[round(0.3 * $r + 0.59 * $g + 0.11 * $b)]++;
				//$hash_string .= sprintf('%02d%02d%02d', (int) $r / 20, (int) $g / 20, (int) $b / 20);			
				//echo(sprintf('%02d%02d%02d<br />', (int) $r / 20, (int) $g / 20, (int) $b / 20));
				//echo($px1.":".$px2."<br>");
				//echo("R: ".$r.", G: ".$g.", B: ".$b."<br>");
				/*if ((abs($r) < 11) && (abs($g) < 11) && (abs($b) < 11)) {
					$success++;
				}		*/
			}
		}
		$dec_num = strlen(self::SIZE ^ 2 / self::THRESHOLD);
		for ($q = 0; $q < 500; $q++) {
			$hash_string .= sprintf('%0'.$dec_num.'d', (int) $histogram[$q] / self::THRESHOLD);			
		}
		//}
		$this->hash = crypt($hash_string, self::$imgSalt);
		return $hash_string;
		//echo($success."<br>".$ptlen."<br>Equality ~".$success / $ptlen * 100 ."%");
		//print_r($cmp_points);
		
		//header("Content-Type: image/png");
		//imagepng($img4);
	}
	
	/*
	 * Поиск ключа в базе
	 */
	public function checkHash() {
		//TODO
	}
	
	/*
	 * Сохранение ключа в базу
	 */
	public function save() {
		try {
			parent::save('hash');
		} catch (Exception $e) {
			throw new Exception('This image is already present in database!');
		}			
	}
	
	/*
	 * Проверим и загрузим изображение для дальнейших действий.
	 */
	public function readImageFile($filename) {
		if (strlen($filename) == 0) {
			die("Файл мне запили!");
		}
		$this->path = $filename;
		$info = getimagesize($filename);	
		//print_r($info);
	    $ext = $info[2];		
		switch($ext)
		{
			case IMAGETYPE_PNG: $this->img = imagecreatefrompng($filename); break;
			case IMAGETYPE_JPEG: $this->img = imagecreatefromjpeg($filename); break;
			case IMAGETYPE_GIF: $this->img = imagecreatefromgif($filename); break;
			default: die("{$ext} не принмаются и даже не рассматриваются.");
		}
	}
	
	public function getClass() {
		return 'image';
	}
}
?>
